import { EditOutlined, SearchOutlined } from "@ant-design/icons";
import { Avatar, Button, Card, Col, Drawer, Form, Modal, Radio, Space, Tooltip } from "antd";
import Meta from "antd/lib/card/Meta";
import Title from "antd/lib/typography/Title";
import { useState } from "react";
import { useNavigate } from "react-router";
import { useSetRecoilState } from "recoil";
import { IExamData } from "../interface";
import { defaultQuestionTypeState } from "../recoil/atoms/examFormAtoms";
import { numToChar } from "../util";

interface ISolveProblem {
  examData: IExamData
}

export default function SolveProblem(props: ISolveProblem) {
  const { examData: { choices, title, analysis, answer, addTime, tag } } = props;
  const [questionDetail, setQuestionDetail] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [showAnswer, setShowAnswer] = useState<boolean>(false);
  const [radioValue, setRadioValue] = useState<string>('');
  const setDefaultQuestionType = useSetRecoilState(defaultQuestionTypeState);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const cancelDetail = () => {
    setQuestionDetail(false);
  };

  const showDetails = () => {
    setQuestionDetail(true);
  };

  const cancelSolveQuestion = () => {
    setVisible(false);
    setShowAnswer(false)
    setRadioValue('')
  };

  const showSolveQuestionDrawer = () => {
    setVisible(true);
  };

  const submitYouAnswer = async () => {
    try {
      await form.validateFields(['selectAnswer']);
      setShowAnswer(true)
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  const renderQuestionItem = () => {
    return (
      <>
        <Title className="h-10 leading-10 px-6 mb-0" level={5}>题目描述：</Title>
        <p className="px-6">{title}</p>
        <Title className="h-10 leading-10 px-6 mb-0" level={5}>题目解析：</Title>
        <p className="px-6">{analysis}</p>
        <Title className="h-10 leading-10 px-6 mb-0" level={5}>选项：</Title>
        {choices?.map((item, index) => {
          return (
            <span className="text-md px-6" key={index}>
              {`${numToChar(index)}. ${item}`}
            </span>
          )
        })}
      </>
    )
  };

  const renderAnswer = () => {
    return (
      <>
        <Title className="h-10 leading-10 px-6 mb-0" level={5}>参考答案：</Title>
        <p className="px-6">{numToChar(answer)}</p>
      </>
    )
  }

  const validateRadio = () => {
    if (!radioValue) {
      return Promise.reject('请选择答案');
    }
    return Promise.resolve();
  }

  return (
    <>
      <Col key={addTime}>
        <Card
          className="min-h-[465px] text-gray-500 rounded-[5px] flex flex-col justify-around shadow-lg"
          title={tag}
          extra={<span className="text-cyan-300 font-bold cursor-pointer" onClick={showDetails}>查看详细</span>}
          cover={
            <div className="min-h-[240px]">
              {
                renderQuestionItem()
              }
            </div>
          }
          actions={[
            <Tooltip title="查找同型题目" color={"cyan"} key="search">
              <SearchOutlined onClick={() => { navigate('examManage'); setDefaultQuestionType(tag) }} />
            </Tooltip>,
            <Tooltip title="我来试试解题" color={"cyan"} key="edit" >
              <EditOutlined onClick={showSolveQuestionDrawer} />
            </Tooltip>,
          ]}
        >
          <p className="text-right text-gray-400">提交时间：{addTime}</p>
          <Meta
            className="b-0"
            avatar={<Avatar src="https://img0.baidu.com/it/u=1694074520,2517635995&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1659027600&t=b8ad63c81bb69f91f216481d29fbe995" />}
            title="作者"
            description="提交者备注"
          />
        </Card>
      </Col>

      {/* 试题详情 */}
      <Modal
        title="试题详情"
        visible={questionDetail}
        centered
        closable={false}
        bodyStyle={{ padding: 0 }}
        footer={
          [
            <Button key="back" onClick={cancelDetail}>
              关闭
            </Button>
          ]
        }
      >
        <div>
          {renderQuestionItem()}
          {renderAnswer()}
        </div>
      </Modal>

      {/* 试一试模板 */}
      <Drawer
        placement="right"
        size="large"
        visible={visible}
        closable={false}
      >
        {renderQuestionItem()}
        <Form form={form}>
          <Title className="h-10 leading-10 px-6 mb-0" level={5}>请做答：</Title>
          <Form.Item name="selectAnswer" rules={[
            {
              validator: validateRadio
            },
          ]}>
            <Radio.Group className="mt-2" value={radioValue} onChange={(e) => { setRadioValue(e.target.value) }}>
              {choices?.map((item, index) => {
                return (
                  <Radio className="text-md px-6" value={index + 1} key={index}>
                    {`${numToChar(index)}. ${item}`}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>
        </Form>
        {
          showAnswer && renderAnswer()
        }
        <Space className="absolute bottom-[35px] right-[35px]">
          <Button onClick={cancelSolveQuestion}>离开</Button>
          <Button type="primary" onClick={submitYouAnswer}>
            提交
          </Button>
        </Space>
      </Drawer>
    </>
  )
}
